<template>
    <div class="box">
        <div class="p-menu flex" v-if="userData.username =='root'">
            <el-select v-model="platformId" placeholder="平台" style="width:100%;" @change="setPlatformId">
                <el-option v-for="item in platformList" :key="item.id" :label="item.name" :value="item.id" >
                </el-option>
            </el-select>
            <el-button style="color: white; margin-left: 10px;" color="#FABD68" @click="getBasics">基础权限</el-button>
        </div>


        <div class="p-menu" style="padding-top:20px;min-height: 570px; background: white;">
            <tree-muen @addend="addend" @deleteMenu="deleteMenu" @propertySet="propertySet" @roleSet="roleSet"
                :dataArray="dataArray" />
            <el-button @click.stop.prevent color="#2CA6E0" @click="addend" style="width: 200px; margin-left: 24px;margin-top: 15px;color: aliceblue;">+</el-button>
        </div>
        
        <!-- 菜单属性 -->
        <el-dialog v-model="dialogVisible" :title="visibleTitle" width="500" class="role-add">
            <el-form :model="form" label-width="120px">
                <el-form-item label="名称">
                    <el-input v-model="form.label" style="width:240px;" placeholder="菜单名称" />
                </el-form-item>
                <el-form-item label="序号">
                    <el-input v-model="form.idx" type="number" style="width: 240px;"/>
                </el-form-item>
                <el-form-item label="路径">
                    <el-input v-model="form.path" placeholder="url"  style="width: 240px;"/>
                </el-form-item>
                <el-form-item label="图标">
                    <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false" :on-success="handleAvatarSuccess" >
                        <img v-if="form.icon" :src="form.icon" class="avatar">
                        <div  v-else class="flex">+</div>
                    </el-upload>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="postSubmit">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>


        <!-- 权限编辑 -->
        <el-dialog v-model="roleVisible" title="权限编辑" width="746" class="role-add">
            <el-button class="flex-right" style="position: absolute;z-index: 10;right: 20px;top: 50px;width: 100px;"
                @click="setRoleAdd()">新增</el-button>
            <el-table :data="roleArray" class="p-ul" v-loading="loading" @row-click="handleRowClick" @click.stop.prevent>
                <el-table-column prop="name" label="名称" align="left" width="180"  >
                    <template #default="scope">
                        <div @click="setRoleAdd(scope.row)" style="cursor: pointer;width: 100%;">{{ scope.row.name }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="cmd" label="权限标识符" align="center " >
                    <template #default="scope">
                        <div @click="setRoleAdd(scope.row)" style="cursor: pointer;width: 100%;">{{ scope.row.cmd }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="url" label="路径" width="100" :show-overflow-tooltip="true" align="center " >
                    <template #default="scope">
                        <div @click="setRoleAdd(scope.row)" style="cursor: pointer;width: 100%;">{{ scope.row.url }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150">
                    <template #default="scope">
                        <img :src="'./img/button-3.png'" style="width: 20px;height: 20px;" @click.stop.prevent
                            @click="deleteMenuAuth(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>

                <span class="dialog-footer">
                    <el-button @click="roleVisible = false">取消</el-button>
                    <el-button type="primary" @click="postSubmit">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog v-model="roleAddVisible" :title="roleAddTitle + '权限'" width="400" class="role-add">
            <el-form :model="form" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="menuAuth.name" placeholder="名称" />
                </el-form-item>
                <el-form-item label="路径">
                    <el-input v-model="menuAuth.url" placeholder="路径" />
                </el-form-item>
                <el-form-item label="权限标识符">
                    <el-input v-model="menuAuth.cmd" placeholder="权限标识符" />
                </el-form-item>
                
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="roleAddVisible = false">取消</el-button>
                    <el-button type="primary" @click="postMenuAuth">
                        确定
                    </el-button>
                </span>
            </template>

        </el-dialog>


    </div>
</template>
  
<script setup>

import {
    ref,
    getCurrentInstance,
    onMounted,
    watch,
    reactive
} from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'

const {
    proxy
} = getCurrentInstance();

const loading = ref(false);

const dataArray = ref([])

//新增or编辑
const dialogVisible = ref(false)
const visibleTitle = ref('');
const roleVisible = ref(false);

const roleArray = ref();
const submitList = ref([]);//集合数据
const total = ref(0);

//新增权限
//菜单权限编辑
const roleAddVisible = ref(false);
const roleAddTitle = ref('');

const menu = ref(
    {id:null}
);//树形返回的数据,菜单属性

const menuAuth = ref({
    id: null,
    menuId: null,
    name: null,
    url: null,
    cmd: null,
})

const getFormId = ref(null);


onMounted(() => {
    getPlatformList();
    //获取缓存数据
    getUser();
});
const userData = ref({});
const platformName = ref('');


//图片上传
function handleAvatarSuccess(res, file) {
    // form.icon = URL.createObjectURL(file.raw);
}
function getUser() {
    const savedData = localStorage.getItem('USERINFO');
    const obj = JSON.parse(savedData);
    userData.value = obj;
    
    // console.log("目录");
    // console.log(obj);
    //console.log(userData.value.username)
    if (userData.value.platform != null) {
        platformName.value = userData.value.platform.name;
        platformId.value = userData.value.platform.id;
    }
    getMenuListTree();

}

function reset() {//重置数据
    form.value = {
        id: null,
        platformId: null,
        parentId: null,
        label: null,
        path: '',
        icon: null,
        idx: null,
        createUserId: null,
        updateUserId: null,
        createTime: null,
        updateTime: null,
    }
    // if (userData.value.platform != null) {
        form.value.platformId = userData.value.platform.id;
    // }
}

//新增
function addend(value) {
    reset();
    visibleTitle.value = '新增'
    dialogVisible.value = true;
    form.value.platformId = platformId.value;
    form.value.parentId = value.parentId;
    // console.log(value);
}
//菜单属性编辑
function propertySet(value) {
    getFormId.value =  value.id;
    getForm();
    visibleTitle.value = '编辑'
    form.value = value;
    dialogVisible.value = true;
}


function setPlatformId(value){
    platformId.value = value;
    getMenuListTree();
}

function handleRowClick(value) {

}


function postSubmit() {//提交菜单
    form.value.platformId = platformId.value;
    proxy.$Request.post(proxy.$urlApi.menu.submit, form.value)
        .then((res) => {
            // form.value = res.data.data;
            if (res.data.code != 200) {
                ElMessage({
                    message: res.data.msg,
                    type: 'error',
                })
            } else {
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                })
                visibleTitle.value = false;
                dialogVisible.value =false;
            }
        }).catch(error => {
            ElMessage({
                message: '提交失败',
                type: 'error',
            })
        }).finally(() => {
        })
}

//新增权限
//菜单权限编辑
function setRoleAdd(index) {
    if (index == null) {
        roleAddTitle.value = '新增'
        resetMenuAuth();
    } else {
        roleAddTitle.value = '编辑'
        menuAuth.value = {
            id:index.id,
            menuId:index.menuId,
            name:index.name,
            url:index.url,
            cmd:index.cmd,
        };
    }
    roleAddVisible.value = true;
}


function roleSet(value) {//树形返回的数据,菜单属性
    roleVisible.value = true;
    menu.value = value;
    getMenuAuth();
}

async function getMenuAuth() {//查询菜单权限
    const data = {
        menuId: menu.value.id == null ? "" : menu.value.id,
        platformId:platformId.value,
    }
    proxy.$Request.get(proxy.$urlApi.auth.list, data)
        .then((res) => {
            // form.value = res.data.data;
            if (res.data.code != 200) {
                ElMessage({
                    message: res.data.msg,
                    type: 'error',
                })
            } else {
                roleArray.value = res.data.data;
            }
        }).catch(error => {
            ElMessage({
                message: '查询失败',
                type: 'error',
            })
        });
}


function resetMenuAuth() {
    menuAuth.value = {
        id: null,
        menuId: null,
        name: null,
        url: null,
        cmd: null,
    }
}
function postMenuAuth() {//提交菜单权限
    const data = {
        id: menuAuth.value.id,
        menuId: menu.value.id,
        name: menuAuth.value.name,
        url: menuAuth.value.url,
        cmd: menuAuth.value.cmd,
        platformId: platformId.value
    }
    proxy.$Request.post(proxy.$urlApi.auth.submit, data)
        .then((res) => {
            // form.value = res.data.data;
            if (res.data.code != 200) {
                ElMessage({
                    message: res.data.msg,
                    type: 'error',
                })

            } else {
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                })
                getMenuAuth();
                roleAddVisible.value = false;

            }


        }).catch(error => {
            ElMessage({
                message: '提交失败',
                type: 'error',
            })
        });
}

function deleteMenuAuth(row) {//删除菜单权限
    ElMessageBox.alert(`是否删除${row.name}?`, '删除提示', {
        confirmButtonText: '确认',
        callback: (action) => {
            if (action === 'confirm') {
                const data = { id: row.id }
                proxy.$Request.delete(proxy.$urlApi.auth.delete, data)
                    .then((res) => {
                        if (res.data.code != 200) {
                            ElMessage({
                                message: res.data.msg,
                                type: 'error',
                            })
                        } else {
                            getMenuAuth();
                            ElMessage({
                                type: 'error',
                                message: '删除操作已完成',
                            })
                            roleAddVisible.value = false;

                        }


                    })

            }
        }
    })

}

async function getForm() {//获取列表数据
    const data = {
        id: getFormId
    };
    // loading.value = true;
    proxy.$Request.get(proxy.$urlApi.menu.select, data)
        .then((res) => {
            total.value = res.data.data.total;
            submitList.value = res.data.data.list;
            loading.value = false;

        }).catch(error => {
            // 处理 Promise 拒绝的情况
            // console.error(error); // 输出错误信息
            loading.value = false;
        });
}





//删除
const deleteVisible = ref(false);


const form = ref({
    name: null,
    platformId: null,

})



//获取平台集合
const platformId = ref();
const platformList = ref([]);
async function getPlatformList() {
    const data = {
        enable: 1
    }
    await proxy.$Request.get(proxy.$urlApi.platform.list, data)
        .then((res) => {
            platformList.value = res.data.data;
            platformId.value = platformList.value[0].id;
        }).catch(error => {
        });
}

//权限
//删除
function deleteMenu(id) {
    const data = {
        id: id
    }
    proxy.$Request.delete(proxy.$urlApi.menu.delete, data)
        .then((res) => {
            if(res.data.code == 200){
                getMenuListTree();
            }else{
                ElMessage({
                message: id + '删除成功',
                type: 'success',
            })
            }
        }).catch(error => {
        });
}


//查询菜单集合menuOptions
async function getMenuListTree() {
    const data = {
        platformId: platformId.value
    }
    proxy.$Request.get(proxy.$urlApi.menu.listTree, data)
        .then((res) => {
            dataArray.value = addNewItemToCollection(res.data.data);
        }).catch(error => {
        });
}
const addNewItemToCollection = (data) => {
    const addNewItemRecursively = (items) => {
        return items.map((item) => {
            const newItem = { ...item };
            if (newItem.children) {
                newItem.children = addNewItemRecursively(newItem.children);
            } else {
                newItem.children = [];
            }
            newItem.children.push({
                id: null,
                label: `parentId: ${item.id}`,
                parentId: item.id,
            });

            return newItem;
        });
    };
    return addNewItemRecursively(data);
};


//获取基础权限
function getBasics(){
    roleVisible.value = true;
    menu.value.id = "";
    getMenuAuth();
}




</script>
<style lang="scss">
// .box {
//     // width: calc(100% - 234px);
// }

.p-menu {
    background: #F9FAFA;
    margin: 30px;
    height: 40px;
    // width:100%;
}

.p-i1,
.p-i2 {
    margin-right: 10px;
    color: black;
    height: 40px;

}

.p-i2 .el-input__wrapper {
    height: 38px;
    width: 194px;
    margin-right: 10px;
    color: black;
}

.p-i1 {
    width: 271.49px;
}


.p-button {
    color: white;
    width: 92px;
    height: 40px;
}

.p-button-m1 {
    color: black;
    border: solid 1px #8d8c8c;
    width: 200px;
    text-align: left;
    height: 40px;
}

.p-button-m2 {
    color: white;
    border: solid 1px #8d8c8c;
    width: 92px;
    height: 40px;

}

.p-button-m3 {
    color: white;
    border: solid 1px #8d8c8c;
    width: 200px;
    text-align: left;
    margin: 10px 0;
}

.el-input__inner::placeholder {
    color: #999 !important;
}


.p-ul-box {
    padding: 0 30px;
}

.s .p-menu-left {
    width: 100%;
    padding-top: 20px;
    padding-bottom: 60px;
    margin-left: -30px;
    padding-left: 30px;
    background: rgba(0, 0, 0, 0.04);

    // background: red ;
}

//列表
.el-table__inner-wrapper {
    height: calc(100vh - 300px);
}

.is-leaf.el-table__cell {
    background: #E7F0F3 !important;

}

.el-table__cell {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
}

.cell {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
}

.el-table__row:nth-child(odd) {
    background-color: #FFFFFF;
    /*奇数行的背景颜色*/
}

.el-table__row:nth-child(even) {
    background-color: #F9FAFA;
    /*偶数行的背景颜色*/
}



.p-end {
    font-size: 10px;
    padding-left: 30px;
    color: #9A9DAA;
    margin-top: 20px;
}

.el-dialog__header {
    font-size: 16px;
}

.el-dialog__footer {
    font-size: 16px;
}

.el-input__wrapper {
    font-size: 16px;
}

.p-button-2 {
    background: #74C8CE;
    color: white;
    width: 92px;
    height: 40px;
}

//权限
.role-add {
    .r-list {
        width: 550px;
        background: #E7F0F3;
        font-size: 16px;
        flex-wrap: wrap;
        min-height: 80px;
        border-radius: 5px;

        .r-li {
            font-size: 14px;
            width: 81px;
            height: 22px;
            background: #5A7C93;
            border-radius: 5px;
            color: #FFFFFF;
            margin: 5px;
            align-items: center;
            cursor: pointer;

            /* 将光标设置为手指 */
            text {
                width: 65px;
                white-space: nowrap;
                /* 防止文本换行 */
                overflow: hidden;
                /* 超出部分隐藏 */
                text-overflow: ellipsis;
                /* 超出部分显示省略号 */
            }

            img {
                width: 14px;
                height: 14px;
            }


        }
    }
}

.el-tree-node__children {
    height: auto;
}



</style>
  
